import java.util.ArrayList;
import java.util.List;

/**
 * @program: LeetCode
 * @description: LeetCode : 257. 二叉树的所有路径
 * @author: WXY
 * @create: 2023-01-16 19:39
 * @Version 1.0
 **/
public class Num257_binaryTreePaths {
    public List<String> binaryTreePaths(TreeNode root) {
        ArrayList<String> list = new ArrayList<>();
        if (root == null) return list;
        ArrayList<Integer> path = new ArrayList<>();
        process(root, path, list);
        return list;
    }

    private void process(TreeNode root, ArrayList<Integer> path, ArrayList<String> list) {
        path.add(root.val);
        if (root.right == null && root.left == null) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < path.size() - 1; i++) {
                sb.append(path.get(i)).append("->");
            }
            sb.append(path.get(path.size() - 1));
            list.add(sb.toString());
            return;
        }
        if (root.left != null) {
            process(root.left, path, list);
            path.remove(path.size() - 1);
        }
        if (root.right != null) {
            process(root.right, path, list);
            path.remove(path.size() - 1);
        }
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {

        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
